﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BPM.Web;
using BPM.Entity;
using BPM.ViewModel;
using BPM.Service;
using System.Web.Script.Serialization;
using BPM.Common;
using System.IO;
using System.Text;

namespace BPM.Controllers
{
    public class MaterialManagementController : InternalViewController
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult AddMaterial()
        {
            SetCategoriesData();
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddMaterial(MaterialDefinition m, AddMaterialViewModel vm)
        {
            SetCategoriesData();

            var res = this.AddMaterialCore(m, vm);
            if (!res)
            {
                this.ViewData["Error"] = res.Message;
                this.ViewData["PreviousData"] = vm;
                return View(m);
            }
            else
            {
                return RedirectToAction(a => a.MaterialManagement.ViewMaterialList);
            }
        }

        private Result AddMaterialCore(MaterialDefinition m, AddMaterialViewModel vm)
        {
            if (string.IsNullOrWhiteSpace(vm.UserCodeValidate)) return "用户条码无效。";

            //Save image
            var files = Request.Files;
            if (files.Count == 0 || string.IsNullOrWhiteSpace(files[0].FileName)) return "没有上传文件";
            var res = SaveImage(files[0], "~/Upload/Images/Material/");
            if (!res) return res;
            m.ImagePath = "~/Upload/Images/Material/" + res.Message;

            m.CreatorId = this.CurrentUser.Id;

            var svc = new MaterialDefinitionService();
            res = svc.Create(m, vm.BarcodeNumber);
            if (!res)
            {
                try
                {
                    System.IO.File.Delete(Server.MapPath(m.ImagePath));
                }
                catch { }
            }
            return res;
        }

        private void SetCategoriesData()
        {
            var svc = new MaterialDefinitionCategoryService();
            var bigCates = svc.GetBigCates().Select(c => new
            {
                value = c.Id,
                text = c.Name,
                subCates = c.SubCategoryList.Select(sc => new
                {
                    pid = c.Id,
                    value = sc.Id,
                    text = sc.Name
                }).ToArray()
            });
            this.ViewData["AllBigCates"] = JsonString(bigCates);
        }

        public ActionResult ViewMaterialList(ViewMaterialListViewModel vm)
        {
            var svc = new MaterialDefinitionService();
            var result = svc.Search(vm.CompanyName, vm.MaterialName, vm.Page.GetValueOrDefault(1), 15);
            this.ViewData["PreviousSeachCondition"] = vm;
            this.ViewData["Models"] = result;
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ModifyMaterial(int id)
        {
            this.SetCategoriesData();

            var svc = new MaterialDefinitionService();
            var entity = svc.GetById(id);
            if (entity == null) return RedirectToAction(a => a.MaterialManagement.ViewMaterialList);

            return View(entity);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ModifyMaterial(MaterialDefinition entity)
        {
            this.SetCategoriesData();

            var svc = new MaterialDefinitionService();
            var oldEntity = svc.GetById(entity.Id);
            if (oldEntity == null) return RedirectToAction(a => a.MaterialManagement.ViewMaterialList);

            //只选择界面上有的属性进行拷贝。
            oldEntity.Brand = entity.Brand;
            oldEntity.CategoryId = entity.CategoryId;
            oldEntity.ContactName = entity.ContactName;
            oldEntity.ContactPhone = entity.ContactPhone;
            oldEntity.DeliverPeriodUnit = entity.DeliverPeriodUnit;
            oldEntity.DeliveryPeriod = entity.DeliveryPeriod;
            oldEntity.Name = entity.Name;
            oldEntity.OtherContact = entity.OtherContact;
            oldEntity.PaymentMode = entity.PaymentMode;
            oldEntity.Price = entity.Price;
            oldEntity.SupplierName = entity.SupplierName;
            oldEntity.Remark = entity.Remark;

            var res = svc.Save(oldEntity);
            if (res)
            {
                return RedirectToAction(a => a.MaterialManagement.ViewMaterialList);
            }
            else
            {
                this.ViewData["Error"] = res.Message;
                return View(oldEntity);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id)
        {
            var svc = new MaterialDefinitionService();
            var res = svc.Delete(id);
            return Json(res);
        }

        /// <summary>
        /// Manager view pending material list which submitted by employe
        /// </summary>
        /// <returns></returns>
        public ActionResult ViewPendingMaterialList(int? pageIndex)
        {
            var svc = new MaterialDefinitionService();
            ViewData["materialList"] = svc.GetPending(pageIndex ?? 1, StaticData.PagingCount);
            return View();
        }

        /// <summary>
        /// Manager view one pending material detailed information and approver/deny this materail
        /// </summary>
        /// <returns></returns>
        public ActionResult ViewPendingMaterial(int? id)
        {
            if (id == null)
            {
                return RedirectToAction(AD.Singleton.MaterialManagement.ViewPendingMaterialList);
            }

            var svc = new MaterialDefinitionService();
            var model = svc.GetById(id.Value);
            return View(model);
        }

        /// <summary>
        /// 审核通过一个物料 (没有对应的view)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ApprovePendingMaterial(int? id)
        {
            if (id != null)
            {
                var svc = new MaterialDefinitionService();
                svc.ApproveMaterial(id.Value);
            }
            return RedirectToAction(AD.Singleton.MaterialManagement.ViewPendingMaterialList);
        }

        /// <summary>
        /// 删除一个待审核的物料 (没有对应的view)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeletePendingMaterial(int? id)
        {
            if (id != null)
            {
                var svc = new MaterialDefinitionService();
                svc.Delete(id.Value);
            }
            return RedirectToAction(AD.Singleton.MaterialManagement.ViewPendingMaterialList);
        }

        /// <summary>
        /// Import material list by excel file
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ImportMaterialList()
        {
            return View();
        }

        /// <summary>
        /// Import material list by excel file
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ImportMaterialList(FormCollection collection)
        {
            var files = Request.Files;
            string extensionName = GetExtensionFileName(files[0].FileName);
            if (extensionName != null && extensionName.Length > 0 && extensionName.ToLower() == "xls")
            {
                if (files.Count == 1 && files[0].ContentLength > 0)
                {
                    //DataStreams.Csv.CsvReader reader = new DataStreams.Csv.CsvReader(files[0].InputStream, Encoding.UTF8);
                    DataStreams.Xls.XlsReader xlsReader = new DataStreams.Xls.XlsReader(files[0].InputStream);
                    System.Data.DataTable table = xlsReader.Table;
                    int successCount = addMaterialDefByExcel(table);
                    ViewData["successCount"] = successCount;
                }
                else
                {
                    ViewData["warning"] = "文件内容为空";
                }
            }
            else
            {
                ViewData["warning"] = "文件格式不正确,请使用excel文件";
            }
            return View();
        }


        private string GetExtensionFileName(string fileName)
        {
            if (!fileName.Contains('.'))
            {
                return null;
            }
            string[] splits = fileName.Split('.');
            string extension = splits[1];
            return extension;
        }

        private int addMaterialDefByExcel(System.Data.DataTable table)
        {
            int counter = 0;
            var cateSvc = new MaterialDefinitionCategoryService();
            var barcodeSvc = new BarcodeService();
            var defSvc = new MaterialDefinitionService();
            var cateList = cateSvc.GetAll();

            #region loop

            bool isFirstRow = true;
            foreach (System.Data.DataRow row in table.Rows)
            {
                //跳过excel的第一行 因为这一行是标题
                if (isFirstRow)
                {
                    isFirstRow = false;
                    continue;
                }

                MaterialDefinition definition = new MaterialDefinition();

                //条码
                //Barcode barcode = new Barcode();
                //barcodeSvc.New(SysBarcodeCategories.MaterialDefinition, out barcode, row[0].ToString());
                //definition.Barcode = barcode;
                string strBarcode = row[0].ToString();

                //物料名称
                definition.Name = row[1].ToString();

                //所属类别 (大类别不是用来给model赋值的,小类别是)
                var cate = cateList.FirstOrDefault(c => c.Name == row[2].ToString());
                if (cate == null)
                {
                    continue;
                }
                var subCate = cate.SubCategoryList.FirstOrDefault(s => s.Name == row[3].ToString());
                if (subCate == null)
                {
                    continue;
                }
                definition.CategoryId = subCate.Id;

                //品牌
                definition.Brand = row[4].ToString();
                //价格
                definition.Price = decimal.Parse(row[5].ToString());
                //供应商名称 
                definition.SupplierName = row[6].ToString();
                //联系人 
                definition.ContactName = row[7].ToString();
                //联系电话
                definition.ContactPhone = row[8].ToString();
                //其他联系方式 
                definition.OtherContact = row[9].ToString();
                //供货周期
                definition.DeliveryPeriod = Convert.ToInt32(row[10]);
                //供货周期单位
                definition.DeliverPeriodUnit = row[11].ToString();
                //付款方式  
                definition.PaymentMode = row[12].ToString();
                //备注
                definition.Remark = row[13].ToString();

                definition.CreatorId = CurrentUser.Id;
                definition.CurrentAmount = 0;
                definition.ImagePath = "~/Images/NoImage.jpg";
                definition.IsApproved = false;

                var result = defSvc.Create(definition, strBarcode);
                if (result.Success)
                {
                    counter++;
                }
            }
            #endregion

            return counter;
        }

    }

    public class MaterialManagementControllerActions : ControllerDefinition<MaterialManagementController>
    {
        public readonly string ViewMaterialList = "ViewMaterialList";
        public readonly string ModifyMaterial = "ModifyMaterial";
        public readonly string AddMaterial = "AddMaterial";
        public readonly string Delete = "Delete";
        public readonly string ViewPendingMaterialList = "ViewPendingMaterialList";
        public readonly string ViewPendingMaterial = "ViewPendingMaterial";
        public readonly string ApprovePendingMaterial = "ApprovePendingMaterial";
        public readonly string DeletePendingMaterial = "DeletePendingMaterial";
        public readonly string ImportMaterialList = "ImportMaterialList";
    }
}
